// 数据同步模块 - 处理本地和服务器数据同步
import baseAPI from './base.js'
import userAPI from './user.js'

class SyncAPI {
    // 从服务器同步数据
    async syncDataFromServer() {
        const currentUser = uni.getStorageSync('currentUser');
        if (!currentUser) {
            throw new Error('未找到当前用户信息');
        }
        
        const userData = JSON.parse(currentUser);
        // 通过邮箱搜索用户信息来获取服务器数据
        return userAPI.searchUsers(userData.email);
    }

    // 检查数据同步状态
    async checkDataSync() {
        try {
            const healthResponse = await baseAPI.get('/health');
            return {
                serverOnline: healthResponse.status === 'ok',
                lastCheck: new Date().toISOString()
            };
        } catch (error) {
            return {
                serverOnline: false,
                lastCheck: new Date().toISOString(),
                error: error.message
            };
        }
    }

    // 获取本地所有用户数据
    getAllLocalData() {
        return {
            users: userAPI.getLocalUsers(),
            userInfo: uni.getStorageSync('currentUser'),
            settings: uni.getStorageSync('user_settings'),
            lastSync: uni.getStorageSync('last_sync_time'),
            syncHistory: uni.getStorageSync('sync_history')
        };
    }

    // 保存同步后的用户数据
    saveSyncedData(data) {
        if (data.users) {
            const existingUsers = userAPI.getLocalUsers();
            const incomingUsers = Array.isArray(data.users)
                ? data.users
                : this.safeParse(data.users, []);
            const mergedUsers = this.mergeUserRecords(existingUsers, incomingUsers);
            userAPI.saveLocalUsers(mergedUsers);
        }

        if (data.userInfo) {
            const incomingInfo = typeof data.userInfo === 'string'
                ? this.safeParse(data.userInfo, {})
                : { ...data.userInfo };

            const existingInfoRaw = uni.getStorageSync('currentUser');
            let mergedInfo = { ...incomingInfo };

            if (existingInfoRaw) {
                const existingInfo = this.safeParse(existingInfoRaw, {});
                mergedInfo = { ...existingInfo, ...incomingInfo };

                if (!mergedInfo.password && existingInfo.password) {
                    mergedInfo.password = existingInfo.password;
                }

                if (!mergedInfo.offline_id && existingInfo.offline_id) {
                    mergedInfo.offline_id = existingInfo.offline_id;
                }

                if (!mergedInfo.id && existingInfo.id) {
                    mergedInfo.id = existingInfo.id;
                }
            }

            uni.setStorageSync('currentUser', JSON.stringify(mergedInfo));
        }

        if (data.settings) {
            uni.setStorageSync('user_settings', data.settings);
        }
        if (data.lastSync) {
            uni.setStorageSync('last_sync_time', data.lastSync);
        }
    }

    // 合并本地和服务器返回的账户数据，优先保留本地密码等敏感字段
    mergeUserRecords(existingUsers = [], incomingUsers = []) {
        const merged = existingUsers.map(user => ({ ...user }));

        incomingUsers.forEach(user => {
            if (!user) {
                return;
            }

            const key = this.getUserMergeKey(user);
            if (!key) {
                merged.push({ ...user });
                return;
            }

            const index = merged.findIndex(existing => this.getUserMergeKey(existing) === key);

            if (index === -1) {
                merged.push({ ...user });
                return;
            }

            const currentUser = merged[index];
            const preservedPassword = currentUser.password;
            const preservedOfflineId = currentUser.offline_id;

            const updatedUser = { ...currentUser, ...user };

            if (!user.password && preservedPassword) {
                updatedUser.password = preservedPassword;
            }

            if (!updatedUser.offline_id && preservedOfflineId) {
                updatedUser.offline_id = preservedOfflineId;
            }

            merged[index] = updatedUser;
        });

        return merged;
    }

    getUserMergeKey(user = {}) {
        if (!user) return null;
        if (user.email) {
            return String(user.email).toLowerCase();
        }
        if (user.id) {
            return String(user.id);
        }
        return null;
    }

    safeParse(value, fallback) {
        if (!value) {
            return Array.isArray(fallback) ? [] : { ...fallback };
        }
        try {
            return JSON.parse(value);
        } catch (error) {
            console.warn('[SyncAPI] JSON parse failed, fallback applied:', error);
            return Array.isArray(fallback) ? [] : { ...fallback };
        }
    }

    // 同步用户数据到服务器
    async syncDataToServer(data, password = null) {
        try {
            // 获取当前用户信息
            const currentUser = uni.getStorageSync('currentUser');
            if (!currentUser) {
                throw new Error('未找到当前用户信息');
            }
            
            const user = JSON.parse(currentUser);
            
            // 如果没有提供密码，提示用户设置密码
            if (!password) {
                throw new Error('PASSWORD_REQUIRED');
            }
            
            // 准备同步数据
            const syncData = {
                offline_id: String(user.offline_id || user.id || userAPI.generateOfflineId()),
                username: user.name,
                email: user.email,
                password: password,
                role: user.role || 'user',
                avatar: user.avatar || '',
                created_at: user.created_at || new Date().toISOString(),
                updated_at: new Date().toISOString()
            };
            
            console.log('同步数据到服务器:', syncData);
            
            // 调用服务器同步接口
            const result = await baseAPI.request('/sync/user', {
                method: 'POST',
                body: JSON.stringify(syncData)
            });
            
            // 如果同步成功，还需要同步头像（如果有的话）
            if (result.success && user.avatar) {
                try {
                    console.log('同步头像到服务器...');
                    await userAPI.updateAvatar(user.email, user.avatar);
                    console.log('头像同步成功');
                } catch (avatarError) {
                    console.warn('头像同步失败，但用户数据同步成功:', avatarError);
                }
            }
            
            return result;
        } catch (error) {
            console.error('数据同步失败:', error);
            throw error;
        }
    }
}

// 创建全局实例
const syncAPI = new SyncAPI();

export default syncAPI; 